﻿//------------------------------------------------------------------------------
// ╭─────────────────────────────╮
// │ ╭─╮     ╭─╮              TM │   ╠═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╣
// │ │ │     │ │                 │                                           ☺  
// │ │ ╰───╮ │ │ ╭─────╮ ╭─────╮ │     Name:Wedn.Net HTTP请求操作助手类  ♮ ♪ ♩
// │ │ ╭─╮ │ │ │ │ ╭─╮ │ │ ╭─╮ │ │                                    ♫ ♭      
// │ │ ╰─╯ │ │ │ │ ╰─╯ │ │ ╰─╯ │ │     Author:iceStone               ♬ ♪       
// │ └─────╯ └─╯ ╰─────╯ ╰───╮ │ │     Chinese:汪磊                              
// │                     ┌───╯ │ │                                              
// │                     ╰─────╯ │   ╠═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╣
// ╰─────────────────────────────╯                                              
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace Wedn.Net.Utility
{
    /// <summary>
    /// HTTP请求操作助手类
    /// </summary>
    public static class HttpHelper
    {
        #region 以GET方式抓取远程页面内容 +static string Get(string url, string data)
        /// <summary>
        /// 以GET方式抓取远程页面内容
        /// </summary>
        /// <param name="url">请求URL地址</param>
        /// <param name="data">参数列表</param>
        /// <example>
        /// string str=HtmlHelper.Get("http://www.wedn.net","{p1:hello,p2:world}");
        /// </example>
        /// <returns>响应资源体</returns>
        public static string Get(string url, string data)
        {
            return Get(url, data, Encoding.UTF8);
        }
        #endregion

        #region 以GET方式抓取远程页面内容 +static string Get(string url, string data, Encoding encoding)
        /// <summary>
        /// 以GET方式抓取远程页面内容
        /// </summary>
        /// <param name="url">请求URL地址</param>
        /// <param name="data">参数列表</param>
        /// <param name="encoding">字符编码</param>
        /// <example>
        /// string str=HtmlHelper.Get("http://www.wedn.net","{p1:hello,p2:world}");
        /// </example>
        /// <returns>响应资源体</returns>
        public static string Get(string url, string data, Encoding encoding)
        {
            string res;
            try
            {
                if (data.Contains("{"))
                    data = data.TrimStart('{').TrimEnd('}').Replace(":", "=").Replace(",", "&").Replace(" ", string.Empty);
                var request = WebRequest.Create(string.Format("{0}?{1}", url, data)) as HttpWebRequest;
                if (request == null) return string.Empty;
                request.Timeout = 19600;
                var response = (HttpWebResponse)request.GetResponse();
                var reader = new StreamReader(response.GetResponseStream(), encoding);
                var sb = new StringBuilder();
                while (-1 != reader.Peek())
                {
                    sb.Append(reader.ReadLine() + "\r\n");
                }
                res = sb.ToString();
                response.Close();
            }
            catch (Exception ee)
            {
                res = ee.Message;
            }
            return res;
        }
        #endregion

        #region 以POST方式抓取远程页面内容 +static string Post(string url, string data)
        /// <summary>
        /// 以POST方式抓取远程页面内容
        /// </summary>
        /// <param name="url">请求URL地址</param>
        /// <param name="data">参数列表</param>
        /// <example>
        /// string str=HtmlHelper.Post("http://www.wedn.net","{p1:hello,p2:world}");
        /// </example>
        /// <returns>响应资源体</returns>
        public static string Post(string url, string data)
        {
            return Post(url, data, Encoding.UTF8);
        }
        #endregion

        #region 以POST方式抓取远程页面内容 +static string Post(string url, string data, Encoding encoding)
        /// <summary>
        /// 以POST方式抓取远程页面内容
        /// </summary>
        /// <param name="url">请求URL地址</param>
        /// <param name="data">参数列表</param>
        /// <param name="encoding">字符编码</param>
        /// <example>
        /// string str=HtmlHelper.Post("http://www.wedn.net","{p1:hello,p2:world}",Encoding.UTF8);
        /// </example>
        /// <returns>响应资源体</returns>
        public static string Post(string url, string data, Encoding encoding)
        {
            string strResult;
            try
            {
                if (data.Contains("{"))
                    data = data.TrimStart('{').TrimEnd('}').Replace(":", "=").Replace(",", "&").Replace(" ", string.Empty);
                var postData = encoding.GetBytes(data);
                var request = WebRequest.Create(url) as HttpWebRequest;
                if (request == null) return string.Empty;
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = postData.Length;
                Stream newStream = request.GetRequestStream();
                newStream.Write(postData, 0, postData.Length); //设置POST
                newStream.Close();
                var response = request.GetResponse() as HttpWebResponse;
                if (response == null) return string.Empty;
                var reader = new StreamReader(response.GetResponseStream(), encoding);
                strResult = reader.ReadToEnd();
            }
            catch (Exception ex)
            {
                strResult = ex.Message;
            }
            return strResult;
        }
        #endregion

        #region 获取远程数据流 +static Stream GetStream(string url, string data)
        /// <summary>
        /// 获取远程数据流
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="data">参数列表</param>
        /// <example>
        /// Stream s = HttpHelper.GetStream("http://www.wedn.net", "{aid:15000102,0.43878429697395826}");
        /// picVerify.Image = Image.FromStream(s);
        /// </example>
        /// <returns>数据流</returns>
        public static Stream GetStream(string url, string data)
        {
            HttpWebRequest request = null;
            HttpWebResponse response = null;
            try
            {
                if (data.Contains("{"))
                    data = data.TrimStart('{').TrimEnd('}').Replace(":", "=").Replace(",", "&").Replace(" ", string.Empty);
                request = WebRequest.Create(string.Format("{0}?{1}", url, data)) as HttpWebRequest;
                if (request == null) return null;
                request.ContentType = "application/x-www-form-urlencoded";
                request.ServicePoint.ConnectionLimit = 300;
                request.Referer = url;
                request.Accept =
                    "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/x-silverlight, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, application/x-silverlight-2-b1, */*";
                request.UserAgent =
                    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)";
                request.Method = "GET";
                response = request.GetResponse() as HttpWebResponse;
                return response == null ? null : response.GetResponseStream();
            }
            catch (Exception e)
            {
                return null;
            }
            finally
            {
                if (request != null)
                    request.Abort();

                if (response != null)
                    response.Close();
            }
        }
        #endregion
    }
}
